/*********************************************************
 *
 * Filename: demo/read_bmp_tofile.c
 *   Author: jmdvirus
 *   Create: 2019年04月24日 星期三 16时51分09秒
 *
 *********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define LOGD(fmt, ...)                                                         \
    do                                                                         \
    {                                                                          \
        printf(fmt, ##__VA_ARGS__);                                            \
    } while (0)

int main(int argc, char **args)
{
    if (argc < 3)
    {
        LOGD("Usage: %s bmpfile savefile\n", args[0]);
        exit(0);
    }

    const char *bmpfile  = args[1];
    const char *savefile = args[2];

    FILE *fin = fopen(bmpfile, "r");
    if (!fin)
    {
        LOGD("open %s fail\n", bmpfile);
        return -1;
    }
    FILE *fo = fopen(savefile, "w");
    if (!fo)
    {
        LOGD("open %s fail\n", savefile);
        return -2;
    }

    struct stat st;
    int         ret = stat(bmpfile, &st);
    if (!ret)
    {
        size_t fsz  = st.st_size;
        char * data = (char *)malloc(fsz);
        size_t n    = fread(data, 1, fsz, fin);
        if (n > 0)
        {
            LOGD("Read out data of %lu\n", n);
            size_t      i           = 0;
            char        chardata[4] = {0};
            const char *definehead =
                "#ifndef __BMPFILE__\n#define __BMPFILE__\n";
            const char *definelast = "\n#endif\n";
            const char *bmpstart   = "\nchar cm_logo_bmp[] = { \n";
            const char *bmpend     = "};\n";
            fwrite(definehead, 1, strlen(definehead), fo);

            fwrite(bmpstart, 1, strlen(bmpstart), fo);
            for (; i < fsz; i++)
            {
                sprintf(chardata, "0x%02x", ((unsigned char *)data)[i]);
                fwrite(chardata, 1, 4, fo);
                if (i != fsz - 1)
                    fwrite(",", 1, 1, fo);
                if (i % 50 == 0)
                    fwrite("\n\t", 1, 1, fo);
            }
            fwrite(bmpend, 1, strlen(bmpend), fo);

            fwrite(definelast, 1, strlen(definelast), fo);
            LOGD("Write done\n");
        }
        free(data);
    }
    else
    {
        LOGD("Error stat file %s\n", bmpfile);
    }

    LOGD("Free \n");
    fclose(fin);
    fclose(fo);

    return 0;
}
